<template>
    <div class="login-container">
      <div class="welcome-content">
        <!-- 左侧展示的欢迎内容 -->
        <h1>Welcome to Doctor Go</h1>
        <h2>Find the best healthcare professionals</h2>
      </div>
      <div class="login-form">
        <!-- 右侧登录框 -->
        <h2>登录</h2>
        <el-form @submit.prevent="login">
          <el-form-item label="Username" required>
            <el-input v-model="username"></el-input>
          </el-form-item>
          <el-form-item label="Password" required>
            <el-input type="password" v-model="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit">Login</el-button>
          </el-form-item>
        </el-form>
        <div class="register-link">
          <span>还没有账户?</span>
          <el-button @click="showRegisterBox" type="text">点我注册</el-button>
        </div>
      </div>
      <div class="rightpad">
        <h1></h1>
      </div>
      
      <el-dialog
        v-model="showRegister"
        title="Register"
        :visible="showRegister"
        @close="closeRegisterBox"
      >
        <!-- 注册弹出框 -->
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="form.confirmPassword"></el-input>
          </el-form-item>
          <el-form-item label="用户类型" prop="userType">
            <el-radio-group v-model="form.userType">
              <el-radio label="Doctor">Doctor</el-radio>
              <el-radio label="Patient">Patient</el-radio>
            </el-radio-group>
          </el-form-item>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeRegisterBox">Cancel</el-button>
            <el-button type="primary" @click="submitForm('form')">Register</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
    <div class="bottompad"></div>
  </template>
  
  <script>
  import { ElButton, ElInput, ElDialog, ElForm, ElFormItem, ElMessage, ElRadio, ElRadioGroup } from 'element-plus';
  import axios from 'axios';
  import router from '@/router';
  import { mapMutations } from 'vuex';
  
  export default {
    components: {
      ElButton,
      ElInput,
      ElDialog,
      ElForm,
      ElFormItem,
      ElRadio,
      ElRadioGroup
    },
    data() {
      const validateUsername = (rule, value, callback) => {
        const usernamePattern = /^[a-zA-Z][a-zA-Z0-9_]*$/;
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }
        if (!usernamePattern.test(value)) {
          return callback(new Error('用户名必须以字母开头，并且只能包含字母、数字和下划线'));
        }
        callback();
      };
  
      const validatePhone = (rule, value, callback) => {
        const phonePattern = /^[0-9]{11}$/;
        if (!value) {
          return callback(new Error('手机号不能为空'));
        }
        if (!phonePattern.test(value)) {
          return callback(new Error('手机号必须是11位数字'));
        }
        callback();
      };
  
      const validateEmail = (rule, value, callback) => {
        const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!value) {
          return callback(new Error('邮箱不能为空'));
        }
        if (!emailPattern.test(value)) {
          return callback(new Error('邮箱格式不正确'));
        }
        callback();
      };
  
      return {
        userType: '',
        username: 'patient',
        password: '123456',
        confirmPassword: '',
        showRegister: false,
        form: {
          username: '',
          phone: '',
          email: '',
          password: '',
          confirmPassword: '',
          userType: ''
        },
        rules: {
          username: [
            { required: true, validator: validateUsername, trigger: 'blur' }
          ],
          phone: [
            { required: true, validator: validatePhone, trigger: 'blur' }
          ],
          email: [
            { required: true, validator: validateEmail, trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          confirmPassword: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            { validator: (rule, value, callback) => {
              if (value !== this.form.password) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
          ],
          userType: [
            { required: true, message: '请选择用户类型', trigger: 'change' }
          ]
        }
      };
    },
    methods: {
      ...mapMutations(['SET_ROLE']),
      login() {
        // 处理登录逻辑，发送请求等
        console.log('Login:', this.username, this.password);
        axios.post('http://localhost:8085/api/user/login', {
          userName: this.username,
          userPassword: this.password
        })
        .then(response => {
          const { code, msg, data } = response.data; // 从 response.data 中解构出 code, msg 和 data
          switch (code) {
            case 0:
              ElMessage.error(msg);
              break;
            case 1:
              ElMessage.success('登录成功！');
              console.log(data);
              let userType = ''; // 在使用之前声明 userType
              if (data.userType == 1) {
                userType = "patient";
              } else if (data.userType == 2) {
                userType = "doctor";
              }
              this.SET_ROLE(userType, data.userId, data.userName);
              router.push('/' + userType);
              break;
            default:
              ElMessage.warning('未知的响应码');
              break;
          }
        })
        .catch(error => {
          ElMessage.error('请求失败，请稍后重试');
          console.error('Login error:', error); // 打印错误信息以便调试
        });
      },
      SET_ROLE(role, userId, userName) {
        this.$store.commit('setUserRole', { role, userId, userName });
      },
      showRegisterBox() {
        this.showRegister = true;
      },
      closeRegisterBox() {
        this.showRegister = false;
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.register();
          } else {
            console.log('表单验证失败');
            return false;
          }
        });
      },
      register() {
        // 处理注册逻辑，发送请求等
        console.log('Register:', this.form.username, this.form.phone, this.form.email);
        const data = {
          username: this.form.username,
          password: this.form.password,
          email: this.form.email,
          telephone: this.form.phone,
          userType: this.form.userType,
        };
        axios.post('http://127.0.0.1:4523/m1/4264981-3906719-default/user/register', data)
        .then(response => {
          ElMessage.success(response.data.message || '注册成功');
          this.closeRegisterBox();
        })
        .catch(error => {
          ElMessage.error('注册失败');
        });
      },
    },
  };
  </script>
  
  <style>
  .login-container {
    display: flex;
    justify-content: space-between;
    background-color: #f2f2f2;
  }
  
  .welcome-content {
    flex: 2;
    padding: 40px;
  }
  
  .login-form {
    margin-top: 20%;
    flex: 0.5;
    padding: 40px;
    background-color: #ffffff;
  }
  
  .register-link {
    margin-top: 20px;
  }
  
  .rightpad {
    flex: 0.5;
  }
  
  .bottompad {
    background: #f2f2f2;
    height: 800px;
  }
  
  .el-dialog__wrapper {
    width: 400px;
  }
  </style>
  